from typing import Any

from sqlalchemy import insert, select, update

from recruit.adapter.database.gateway.base import SQLAlchemyGateway
from recruit.adapter.database.models import User
from recruit.adapter.stubs import StubUserGateway
from recruit.domain.models.user_id import UserId


class UserGateway(SQLAlchemyGateway, StubUserGateway):
    async def get_one(self, **kwargs: Any) -> User | None:
        stmt = select(User).filter_by(**kwargs)
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()

    async def create(self, **kwargs: Any) -> User:
        stmt = insert(User).values(**kwargs).returning(User)
        result = await self.session.execute(stmt)
        return result.scalar_one()

    async def update(self, id: UserId, **kwargs: Any) -> User:
        stmt = update(User).values(**kwargs).where(
            User.id == id
        ).returning(User)
        result = await self.session.execute(stmt)
        return result.scalar_one()

    async def check_user(self, **kwargs: Any) -> bool:
        stmt = select(User).filter_by(**kwargs).exists()
        return await self.session.scalar(select(stmt))
